<template>
  <page-wrap
    :bgColor="dynamicColor"
    txtColor="#222"
    :showTop="false"
    :dark="true"
    back
    hideTab
  >
    <view
      class="simple-career-path-report"
      :style="'padding-top:' + navHeight + 'px;'"
    >
      <view class="title-box">
        <view class="title"> 职途报告 </view>
        <view class="title-desc"> 为你量身打造的成长指南 </view>
      </view>
      <u-form :model="form" ref="uForm" label-position="top" class="form">
        <block v-for="(item, index) in formList" :key="index">
          <view class="form-item-wrap" @click.capture="handleSelect(index)">
            <u-form-item
              :class="[
                { pick: item.comp !== 'input' },
                { multiple: item.multiple },
              ]"
              :label="item.label"
              :prop="item.prop"
              :border-bottom="!item.hideBorderBottom"
              :required="item.required"
            >
              <u-input
                v-if="item.comp === 'input'"
                class="form-input"
                v-model="form[item.prop]"
                :placeholder="item.inputPlaceholder"
                :clearable="false"
                adjust-position
                :maxlength="20"
              />
              <u-input
                v-if="item.comp === 'select'"
                :class="['form-input']"
                v-model="form[item.prop]"
                :disabled="!!item.comp"
                :placeholder="item.inputPlaceholder"
                :type="item.inputType"
                :height="item.height"
                :maxlength="item.maxlength || 150"
                :clearable="false"
                :id="item.prop"
              />
            </u-form-item>
          </view>
        </block>
      </u-form>
      <view class="footer">
        <view class="btn" @click="handleSubmit">去使用</view>
      </view>
    </view>
    <MajorListPopup
      :show.sync="showMajorList"
      @close="handleCloseMajorListPopup"
      @emitParams="handleGetMajorParams"
    ></MajorListPopup>
    <WantJobPopup
      :show.sync="showWantJob"
      @close="handleCloseWantJobPopup"
      @emitParams="handleGetWantJobParams"
    ></WantJobPopup>
    <LoginDialog
      ref="loginDialog"
      @loginSuccessBack="loginSuccessBack"
    ></LoginDialog>
  </page-wrap>
</template>

<script>
import {
  getUserInfo,
  cardRegist,
  addPersonTrend,
  getSimpleCareerUserInfo,
  updateSimpleCareerUserInfo,
} from '@/api/modules/career';
import MajorListPopup from './components/MajorListPopup';
import WantJobPopup from './components/WantJobPopup';
import LoginDialog from '@/components/LoginDialog';
import ShareMixin from '@/mixins/share';
import WxLoginMixin from '@/mixins/wxLogin';
import { env } from '@/api/root';
export default {
  name: 'newResume',
  components: {
    MajorListPopup,
    WantJobPopup,
    LoginDialog,
  },
  mixins: [WxLoginMixin, ShareMixin],
  data() {
    return {
      navHeight: getApp().globalData.navHeight,
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      appendixImg: this.$imgBaseSelf + 'resume/appendix_new.svg',
      dynamicColor: 'transparent',
      shareTitle: '为你量身打造的成长指南', // 分享自定义标题
      sharePath: '/pagesSub/SimpleCareerPathReport/index',
      imageUrl: '',
      form: {
        personName: '',
        major: '',
        position: '',
      },
      formList: [
        {
          label: '姓名',
          prop: 'personName',
          propVal: 'personName',
          comp: 'input',
          inputPlaceholder: '必填',
          required: true,
        },
        {
          label: '选择专业',
          prop: 'major',
          propVal: 'major',
          comp: 'select',
          show: false,
          inputPlaceholder: '必填',
          required: true,
        },
        {
          label: '选择求职意向',
          prop: 'position',
          propVal: 'position',
          comp: 'select',
          show: false,
          inputPlaceholder: '必填',
          required: true,
        },
      ],
      rules: {
        personName: [
          {
            required: true,
            message: '请填写姓名',
          },
        ],
        major: [
          {
            required: true,
            message: '请选择专业',
          },
        ],
        position: [
          {
            required: true,
            message: '请选择求职意向',
          },
        ],
      },
      showMajorList: false,
      showWantJob: false,
      resumeParams: {},
      majorParams: {},
      wantJobParams: {},
      timer: null,
      retryCount: 0,
      MAX_RETRY_TIMES: 5,
      resumeHasAnalysis: false,
      zwId: '',
      tradeName: '',
      positionId: '',
    };
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onShow() {
    uni.$on('wantJobUpdate', () => {
      this.showWantJob = true;
    });
    uni.$on('majorListUpdate', () => {
      this.showMajorList = true;
    });
  },
  onLoad(opt) {
    // imageUrl必须在这里赋值，要不然分享的图片是空的
    // this.imageUrl =
    //   "https://img3.job1001.com/ypMp/elan/images/career/AIResumeDiagnoseNewShare_cover.png";
    if (!this.personId) {
      this.showLoginDialog();
      return;
    }
    this.getSimpleCareerUserInfoFn();
    this.freshData();
  },
  onUnload() {
    uni.$off('wantJobUpdate');
    uni.$off('majorListUpdate');
  },
  created() {},
  methods: {
    freshData() {
      this.sharePath = '/pagesSub/SimpleCareerPathReport/index';
    },
    async cardRegistFn() {
      const params = {
        personId: this.personId,
      };
      if (env == 'test') {
        params.cardType = 54;
      } else if (env == 'pro') {
        params.cardType = 28;
      }
      const res = await cardRegist(params);
      return res;
    },
    async loginSuccessBack() {
      this.personId = uni.getStorageSync('person-id').slice(2) || '';
      await this.getUserInfoFn();
    },
    async getUserInfoFn() {
      uni.showLoading({ title: '' });
      // 这个uid一定要传，因为在interceptors中，没有传参的请求的请求头不会带上uid，而这个请求一定要uid
      const res = await getUserInfo({ uid: '' });
      if (res.code == 200) {
        uni.setStorageSync('personName', res.data.personName);
        uni.setStorageSync('cardType', res.data.cardType);
        this.form.personName = res.data.personName;
        //如果没有cardType就绑定一个q2c端的
        if (res.data && !res.data.cardType) {
          const registerRes = await this.cardRegistFn();
          uni.hideLoading();
          if (registerRes.code != 200) {
            uni.showToast({
              title: registerRes.status_desc,
              icon: 'none',
            });
          } else if (registerRes.code == 200) {
            const infoRes = await getUserInfo({ uid: '' });
            if (infoRes.code == 200) {
              uni.setStorageSync('personName', infoRes.data.personName);
              uni.setStorageSync('cardType', infoRes.data.cardType);
            }
          }
        } else {
          uni.setStorageSync('personName', res.data.personName);
          uni.setStorageSync('cardType', res.data.cardType);
        }
      }
    },
    showLoginDialog() {
      this.$refs.loginDialog.setVisibility(true);
    },
    handleSelect(index) {
      switch (index) {
        case 1:
          this.showMajorList = true;
          break;
        case 2:
          this.showWantJob = true;
          break;
        default:
          break;
      }
    },
    handleGetMajorParams(val) {
      if (val) {
        this.majorParams = JSON.parse(val);
        this.form.major = this.majorParams.major;
      }
      this.showMajorList = false;
    },
    handleCloseMajorListPopup() {
      this.showMajorList = false;
    },
    handleGetWantJobParams(val) {
      if (val) {
        this.wantJobParams = JSON.parse(val);
        this.form.position = this.wantJobParams.zwname;
        this.tradeName = this.wantJobParams.tradeName;
        this.zwId = this.wantJobParams.zwid;
      }
      this.showWantJob = false;
    },
    handleCloseWantJobPopup() {
      this.showWantJob = false;
    },
    handleSubmit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.addPersonTrendFn();
          this.updateSimpleCareerUserInfoFn();
        } else {
          console.log('验证失败');
        }
      });
    },
    updateSimpleCareerUserInfoFn() {
      const params = {
        personId: this.personId,
        personName: this.form.personName,
      };
      updateSimpleCareerUserInfo(params).then((res) => {
        if (res.code != 200) {
          uni.showToast({
            title: res.status_desc,
            icon: 'none',
          });
        }
      });
    },
    getSimpleCareerUserInfoFn() {
      getSimpleCareerUserInfo({ personId: this.personId }).then((res) => {
        if (res.code == 200) {
          this.form.personName = res.data.personName;
        }
      });
    },
    addPersonTrendFn() {
      const params = {
        zwId: this.zwId,
        zwName: this.form.position,
        tradeName: this.tradeName,
      };
      addPersonTrend(params).then((res) => {
        if (res.code == 200 && res.data.positionId) {
          this.positionId = res.data.positionId;
          const query = `positionName=${this.form.position}&positionId=${this.positionId}&personName=${this.form.personName}&major=${this.form.major}`;
          uni.navigateTo({
            url: `/pagesSub/SimpleCareerPathReport/simpleCareerPathDetail?${query}`,
          });
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: 'none',
            duration: 2000,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base: $img-base;

.simple-career-path-report {
  min-height: 100vh;
  background-color: #fdfeff;
  padding: 0 32rpx;
  color: $uni-text-color-333;
  position: relative;
  padding-bottom: calc(42rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(42rpx + env(safe-area-inset-bottom));
  background-image: url($img-base + 'resume/newResumeBG.png');
  background-size: 100% auto;
  background-repeat: no-repeat;

  .title-box {
    margin: 58rpx 0 138rpx 0;
    .title {
      font-size: 48rpx;
      font-weight: 600;
      color: #222;
    }
    .title-desc {
      font-size: 28rpx;
      color: #333;
      margin-top: 18rpx;
    }
  }
  .form {
    ::v-deep .u-form {
      margin-left: 15rpx;
    }
    ::v-deep .u-form-item {
      padding: 44rpx 0;
    }
    ::v-deep .u-form-item--left__content__label {
      font-size: 36rpx;
      color: #222222;
    }
  }
  .footer {
    width: 100%;
    height: 80rpx;
    position: fixed;
    bottom: calc(36rpx + constant(safe-area-inset-bottom));
    bottom: calc(36rpx + env(safe-area-inset-bottom));
    .btn {
      width: calc(100% - 64rpx);
      border-radius: 12rpx;
      background: #f75a3e;
      color: #fff;
      text-align: center;
    }
  }
}
</style>
